//
//  CHQueryViewController.m
//  CarFile
//
//  Created by 陈浩 on 2017/3/20.
//  Copyright © 2017年 陈浩. All rights reserved.
//

#import "CHQueryViewController.h"
#import "CHRepairDetailController.h"
#import "CHWXJLDetailsViewController.h"
#import "CHRepairCell.h"
#import "CHTextField.h"
#import "CHQueryViewCell.h"
#import "CHHomeViewCell.h"
#import "CHTitleView.h"
#import "CHWXJLCell.h"
#import "CHWXQYCell.h"
#import "QY_Model.h"
#import "JL_Model.h"

@interface CHQueryViewController ()<UITableViewDelegate,UITableViewDataSource,CHTitleViewDelegate,UITextFieldDelegate>
{
    NSInteger currentIndex;
    BOOL isLoad;
}
@property (nonatomic ,strong) UITableView *jl_tableView;
@property (nonatomic ,strong) UITableView *qy_tableView;
@property (nonatomic ,strong) CHTitleView *titleView;
@property (nonatomic ,strong) UIScrollView *mainScrollView;
@property (nonatomic ,strong) CHTextField *searchField;
@property (nonatomic ,strong) NSMutableArray *qyDatas;
@property (nonatomic ,strong) NSMutableArray *jlDatas;
@property (nonatomic ,strong) NSMutableArray *searchData;
@property (nonatomic ,assign) int index;
@property (nonatomic ,assign) int page;    // 页码
@end

@implementation CHQueryViewController
-(NSMutableArray *)qyDatas{
    if (!_qyDatas) {
        _qyDatas = [NSMutableArray array];
    }
    return _qyDatas;
}

-(NSMutableArray *)jlDatas{
    if (!_jlDatas) {
        _jlDatas = [NSMutableArray array];
    }
    return _jlDatas;
}

-(NSMutableArray *)searchData{
    if (!_searchData) {
        _searchData = [NSMutableArray array];
    }
    return _searchData;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor colorWithHexString:@"eeeef0" alpha:1.0f];
    isLoad = NO;
    currentIndex = 100;
    _isWXJL = NO;
    _isWXQY = NO;
    // 设置标题菜单
    [self setupTitleView];
    
    //  设置查询搜索框
    [self setupSearchView];
    
    //  设置滚动区域
    [self setupMainScrollView];
    
    if (_mark == 2) {
        
        UIButton *btn = (UIButton *)[self.titleView viewWithTag:101];
        [self.titleView titleBtnClick:btn];
        self.searchField.text = nil;
        [self.jl_tableView.mj_header beginRefreshing];
        
    }else if (_mark == 1){
        UIButton *btn = (UIButton *)[self.titleView viewWithTag:100];
        [self.titleView titleBtnClick:btn];
        
    }

}

-(void)setupMainScrollView{
    
  
    
    UIScrollView *mainScrollview = [[UIScrollView alloc] initWithFrame:CGRectMake(0,  CGRectGetMaxY(self.searchField.frame) + 10, UIScreenW, UIScreenH - CGRectGetMaxY(self.searchField.frame) - 10 -64 - 44)];
    mainScrollview.delegate = self;
    mainScrollview.pagingEnabled = YES;
    mainScrollview.scrollEnabled = YES;
    mainScrollview.bounces = NO;
    mainScrollview.showsHorizontalScrollIndicator = NO;
    mainScrollview.showsVerticalScrollIndicator = NO;
//    mainScrollview.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleWidth;
    [self.view addSubview:mainScrollview];
    self.qy_tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, UIScreenW, mainScrollview.h)];
    self.qy_tableView.backgroundColor = KRGB(239, 239, 249);
    self.qy_tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    self.qy_tableView.delegate = self;
    self.qy_tableView.dataSource = self;
    // 下拉刷新
    self.qy_tableView.mj_header= [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        // 模拟延迟加载数据，因此2秒后才调用（真实开发中，可以移除这段gcd代码）
        
        [self getWXQYData];
        
    }];
    self.qy_tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        [self loadMoreWXQYData];
    }];
    self.qy_tableView.mj_footer.automaticallyHidden = YES;
    [mainScrollview addSubview:self.qy_tableView];
    [self.qy_tableView.mj_header beginRefreshing];
    self.jl_tableView = [[UITableView alloc] initWithFrame:CGRectMake(UIScreenW, 0, UIScreenW, mainScrollview.h)];
    self.jl_tableView.backgroundColor = KRGB(239, 239, 249);
    // 下拉刷新
    self.jl_tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    self.jl_tableView.mj_header= [MJRefreshNormalHeader headerWithRefreshingBlock:^{
       
    
        [self getWXJLData];
        
    }];
    self.jl_tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        [self loadMoreWXJLData];
    }];
    self.jl_tableView.mj_footer.automaticallyHidden = YES;
    self.jl_tableView.delegate = self;
    self.jl_tableView.dataSource = self;
    [mainScrollview addSubview:self.jl_tableView];
    
    mainScrollview.contentSize = CGSizeMake(UIScreenW *2, 0);
    self.mainScrollView = mainScrollview;
    
 
}



-(void)setupSearchView{
    
    CHTextField *searchField = [[CHTextField alloc] initWithFrame:CGRectMake(15, 10, UIScreenW - 15 - 60, 34)];
    searchField.layer.cornerRadius = 5;
    searchField.layer.masksToBounds = YES;
    searchField.layer.borderWidth = 1;
    searchField.layer.borderColor = [UIColor colorWithHexString:@"d1d1d1" alpha:1.0f].CGColor;
    searchField.textField.placeholder = @"请输入维修企业名称搜索";
    searchField.backgroundColor = [UIColor whiteColor];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(textFieldDidChange:)
                                                name:UITextFieldTextDidChangeNotification
                                              object:searchField.textField];
    [self.view addSubview:searchField];
    self.searchField = searchField;
    
    UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(CGRectGetMaxX(searchField.frame), 10, 60, 34)];
    btn.titleLabel.font = [UIFont systemFontOfSize:15];
    [btn setTitle:@"搜索" forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor colorWithHexString:@"999999" alpha:1.0f] forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(searchResult) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn];
    
}


-(void)setupTitleView{
    
    NSArray *titles = @[@"维修企业",@"维修记录"];
    CHTitleView *titleView = [[CHTitleView alloc] initWithFrame:CGRectMake(0, 0, 180, 40) withTitles:titles];
    titleView.delegate = self;
    self.navigationItem.titleView = titleView;
    self.titleView = titleView;
    
}


-(void)didBtnClickWithTag:(NSInteger)tag{
    currentIndex = tag;
    [self.mainScrollView setContentOffset:CGPointMake(( tag - 100) *UIScreenW, 0) animated:YES];
    
    self.searchField.text = nil;
    self.searchField.textField.text = nil;
    if (tag == 100) {
        self.searchField.textField.placeholder = @"请输入维修企业名称搜索";
       
        [self getWXQYData];
    
        
    }else{
        
       self.searchField.text = nil;
        
        if (!isLoad) {
     
            [self.jl_tableView.mj_header beginRefreshing];
        }else{
            
            
                [self getWXJLData];
            
        }
    
        self.searchField.textField.placeholder = @"请输入车牌号搜索";

    }
}




-(void)searchResult{
    
    NSLog(@"搜索");
    [MBProgressHUD showMessage:@"数据加载中..."];
    if (currentIndex == 100) {
        
       [self getWXQYData];
    }else{
    
       [self getWXJLData];
    }
}



//获取当前前一天时间
-(NSString *)getCurrentTime {
    
    NSDate * date = [NSDate date];//当前时间
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd"];
    NSString *dateTime = [formatter stringFromDate:date];
    return dateTime;
}


-(void)loadMoreWXJLData{
    
    _index++;
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"areaid"] = [Util getValue:@"areaid"];
    params[@"usertype"] = [Util getValue:@"usertype"];
    if (self.searchField.text.length >= 17) {
        params[@"vin"] = self.searchField.text;
    }else{
        params[@"carno"] = self.searchField.text;
    }
    params[@"user"] = [Globle getInstance].user;
    params[@"sign"] = [DESCript encrypt:(NSString *)[Util getValue:@"areaid"] encryptOrDecrypt:kCCEncrypt key:[Globle getInstance].key];
    params[@"start"] = [Util getStartTime];
    params[@"end"] = [self getCurrentTime];
    params[@"pagesize"] = @"20";
    params[@"pagenum"] = [NSString stringWithFormat:@"%d",_index];
    
    [[Globle getInstance].service requestWithServiceName:@"lcipappgovrecordlist" params:params httpMethod:@"POST" resultIsDictionary:YES completeBlock:^(id result) {
            NSLog(@"%@",result);
        [self.jl_tableView.mj_footer endRefreshing];
        if ([result[@"code"] isEqualToString:@"1"]) {
            for (NSDictionary *dict in result[@"data"][@"repairlist"]) {
                JL_Model *model = [JL_Model objectWithKeyValues:dict];
                [self.jlDatas addObject:model];
            }
            [self.jl_tableView reloadData];
        }
    }];
}




-(void)getWXJLData{
    _index = 1;
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"areaid"] = [Util getValue:@"areaid"];
    params[@"usertype"] = [Util getValue:@"usertype"];
    
    if (self.searchField.text.length >= 17) {
        params[@"vin"] = self.searchField.text;
    }else{
        params[@"carno"] = self.searchField.text;
    }
    params[@"user"] = [Globle getInstance].user;
    params[@"sign"] = [DESCript encrypt:(NSString *)[Util getValue:@"areaid"] encryptOrDecrypt:kCCEncrypt key:[Globle getInstance].key];
    params[@"start"] = [Util getStartTime];
    params[@"end"] = [self getCurrentTime];
    params[@"pagesize"] = @"20";
    params[@"pagenum"] = [NSString stringWithFormat:@"%d",_index];
    
    [[Globle getInstance].service requestWithServiceName:@"lcipappgovrecordlist" params:params httpMethod:@"POST" resultIsDictionary:YES completeBlock:^(id result) {
      NSLog(@"%@",result);
        [MBProgressHUD hideHUD];
        [self.jlDatas removeAllObjects];
        [self.jl_tableView.mj_header endRefreshing];
        if ([result[@"code"] isEqualToString:@"1"]) {
            for (NSDictionary *dict in result[@"data"][@"repairlist"]) {
                JL_Model *model = [JL_Model objectWithKeyValues:dict];
                [self.jlDatas addObject:model];
            }
           
        }
        self.jl_tableView.placeholderImage = @"data_null";
        self.jl_tableView.placeholder = @"非常抱歉，没有找到相关维修记录";
        [self.jl_tableView reloadData];
    }];
    isLoad = YES;
    
}


-(void)loadMoreWXQYData{
    _page++;
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"areaid"] = [Util getValue:@"areaid"];
    params[@"usertype"] = [Util getValue:@"usertype"];
    params[@"company"] = self.searchField.text;
    params[@"user"] = [Globle getInstance].user;
    params[@"sign"] = [DESCript encrypt:(NSString *)[Util getValue:@"areaid"] encryptOrDecrypt:kCCEncrypt key:[Globle getInstance].key];
    params[@"pagesize"] = @"20";
    params[@"pagenum"] = [NSString stringWithFormat:@"%d",_page];
    
    [[Globle getInstance].service requestWithServiceName:@"lcipappgovcompanylist" params:params httpMethod:@"POST" resultIsDictionary:YES completeBlock:^(id result) {
      
        [MBProgressHUD hideHUD];
        [self.qy_tableView.mj_footer endRefreshing];
        [super showLoading:NO];
        if ([result[@"code"] isEqualToString:@"1"]) {
            for (NSDictionary *dict in result[@"data"][@"list"]) {
                QY_Model *model = [QY_Model objectWithKeyValues:dict];
                [self.qyDatas addObject:model];
            }
            
            [self.qy_tableView reloadData];
        }
    }];
    
}


-(void)getWXQYData{
    _page = 1;
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"areaid"] = [Util getValue:@"areaid"];
    params[@"usertype"] = [Util getValue:@"usertype"];
    params[@"company"] = self.searchField.text;
    params[@"user"] = [Globle getInstance].user;
    params[@"sign"] = [DESCript encrypt:(NSString *)[Util getValue:@"areaid"] encryptOrDecrypt:kCCEncrypt key:[Globle getInstance].key];
    params[@"pagesize"] = @"20";
    params[@"pagenum"] = [NSString stringWithFormat:@"%d",_page];

    [[Globle getInstance].service requestWithServiceName:@"lcipappgovcompanylist" params:params httpMethod:@"POST" resultIsDictionary:YES completeBlock:^(id result) {
       
        NSLog(@"维修企业%@",result);
        [MBProgressHUD hideHUD];
        [self.qyDatas removeAllObjects];
        [self.qy_tableView.mj_header endRefreshing];

        if ([result[@"code"] isEqualToString:@"1"]) {
            for (NSDictionary *dict in result[@"data"][@"list"]) {
                QY_Model *model = [QY_Model objectWithKeyValues:dict];
                [self.qyDatas addObject:model];
            }
        }
        self.qy_tableView.placeholderImage = @"data_null";
        self.qy_tableView.placeholder = @"非常抱歉，没有找到相关维修企业";
        [self.qy_tableView reloadData];
    }];
    
}



#pragma mark - UIScrollViewDelegate
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    
    if (scrollView == self.mainScrollView) {
       
        int tag = (int)scrollView.contentOffset.x/self.view.size.width +100 ;
        
        UIButton *btn = (UIButton *)[self.titleView viewWithTag:tag];
        
        
        [self.titleView titleBtnClick:btn];
    }

}





#pragma mark - UITableViewDataSource
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
 
    if (tableView == self.jl_tableView) {
        return self.jlDatas.count;
    }else{
        return self.qyDatas.count;
    }
    
    
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (tableView == self.jl_tableView) {
        CHWXJLCell *cell = [CHWXJLCell cellForTableView:tableView];
        cell.model = self.jlDatas[indexPath.row];
        return cell;
    }else{
        
        NSString *usertype = (NSString *)[Util getValue:@"usertype"];
        if ([usertype isEqualToString:@"99"]) {
            CHWXQYCell *cell = [CHWXQYCell cellForTableView:tableView];
            cell.model = self.qyDatas[indexPath.row];
            return cell;
            
        }else{
            
            CHRepairCell *cell = [CHRepairCell cellForTableView:tableView];
            cell.model = self.qyDatas[indexPath.row];
            cell.scoreNum = 0;
            return cell;
        }
  
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (tableView == self.jl_tableView) {
        return 100;
    }
    return 130;
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView == self.jl_tableView) {
        
        
        id obj = [LongriseRouter openURL:@"CHWXJLDetailsViewController"];
        if(obj && [obj isKindOfClass:[UIViewController class]])
        {
            UIViewController *vc = obj;
            [self.navigationController pushViewController:vc animated:YES];
        }
        
        //判断该类是否可以传参数
        if([LongriseRouter isImplLongriseRouterDelegaterWithObject:obj])
        {
            id<LongriseRouterDelegater> delegater = obj;
            if(delegater)
            {
                
                NSMutableDictionary *params = [NSMutableDictionary dictionary];
              
                params[@"model"] = self.jlDatas[indexPath.row];
                
                //进行传值，传入统一的block以供B进行回调
                [delegater setParams:params block:^(id obj) {
                    
                    
                }];
            }
        }
        
        
    }else{
        
        
        id obj = [LongriseRouter openURL:@"CHRepairDetailController"];
        if(obj && [obj isKindOfClass:[UIViewController class]])
        {
            UIViewController *vc = obj;
            [self.navigationController pushViewController:vc animated:YES];
        }
        
        //判断该类是否可以传参数
        if([LongriseRouter isImplLongriseRouterDelegaterWithObject:obj])
        {
            id<LongriseRouterDelegater> delegater = obj;
            if(delegater)
            {
                
                QY_Model *model = self.qyDatas[indexPath.row];
                NSMutableDictionary *params = [NSMutableDictionary dictionary];
                
                params[@"companyid"] = model.companyid;
                params[@"areaid"] = model.areaid;
                
                //进行传值，传入统一的block以供B进行回调
                [delegater setParams:params block:^(id obj) {
                    
                    
                }];
            }
        }
        
    }

    
    
    
}

//
//补全分割线
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([cell respondsToSelector:@selector(setSeparatorInset:)])
    {
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
    if ([cell  respondsToSelector:@selector(setPreservesSuperviewLayoutMargins:)])
    {
        [cell setPreservesSuperviewLayoutMargins:NO];
    }
    if ([cell respondsToSelector:@selector(setLayoutMargins:)])
    {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(clickWXJL) name:@"changeToWXJL" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(clickWXQY) name:@"changeToWXQY" object:nil];
}


-(void)textFieldDidChange:(NSNotification *)notification
{
    
    UITextField *textField =[notification object];
    if ([textField.text isEqualToString:@""]) {
        if (currentIndex == 100) {
            
            [self getWXQYData];
        }else{
            
            [self getWXJLData];
        }
    }
}



-(void)clickWXJL{
    
    UIButton *btn = (UIButton *)[self.titleView viewWithTag:101];
    [self.titleView titleBtnClick:btn];
    self.searchField.text = nil;
    [self.jl_tableView.mj_header beginRefreshing];
}



-(void)clickWXQY{
    
    UIButton *btn = (UIButton *)[self.titleView viewWithTag:100];
    [self.titleView titleBtnClick:btn];
}


-(void)dealloc{
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end
